/*
 * author      : 吴中勤 
 * date        : 2018/8/22
 * description : 物料转换 sap -> moby
 */

package com.deepexi.adapter.rest.sap.parser;

import com.deepexi.adapter.common.StringUtil;
import com.deepexi.adapter.facade.sap.request.SapPushBaseBody;
import com.deepexi.adapter.sdk.sap.SapBizConst;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class BaseParser<T, R extends SapPushBaseBody> {

    protected Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    protected List<String> keyNumList;
    protected List<T> mobyRequestBodyList = new ArrayList<>();

    public List<String> getKeyNumList() {
        return keyNumList;
    }

    public List<T> getMobyRequestBodyList() {
        return mobyRequestBodyList;
    }


    /**
     * 将sap入参, 进行解析, 得到moby请求入参
     * 并得到回调参数
     */
    public final void parse(String json) {
        // step10 输入参数处理
        if (StringUtil.isNullorEmpty(json)) {
            logger.error("parse JSON, json is empty or null");
            return;
        }

        List<R> sapList = parseSapList(json);

        if (null == sapList || 0 == sapList.size()) {
            logger.error("sapList is empty or null");
            return;
        }

        // step20 准备 moby调用参数 和 回调SAP的结果
        Map<String, Integer> uniqueKeyNum = new HashMap<>();
        sapList.forEach(sapItem -> {
            uniqueKeyNum.put(sapItem.getKeyNum(), 1);
            convertEachSapItem(sapItem);
        });

        if (logger.isDebugEnabled() && sapList.size() > 0) {
            logger.debug(sapList.get(0).toString());
        }

        keyNumList = new ArrayList<String>(uniqueKeyNum.keySet());
    }

    /** 从入参json中, 获取 sapItem 列表 */
    private List<R> parseSapList(String json) {
        List<R> sapList = null;
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray records = jsonObject.getJSONArray(SapBizConst.RESPONSE_NODE_RECORDS);
            String recordsStr = records.toString();

//            以下方法范型不支持, 只能从子类中获取
//            Type collectionType = new TypeToken<List<R>>() {
//            }.getType();
//            sapList = new Gson().fromJson(recordsStr, collectionType);
            sapList = parseSapListFromRecordsStr(recordsStr);
        } catch (Exception ex) {
            logger.error("parse JSON exception", ex);
        }
        return sapList;
    }

    // 处理每个 sapItem
    protected abstract void convertEachSapItem(R sapItem);

    protected abstract List<R> parseSapListFromRecordsStr(String recordsStr);
}
